//
//  ComposeViewController.swift
//  LVWeibo
//
//  Created by lv on 15/7/7.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

// 微博文字的最大长度
private let statusMaxLength = 140

class ComposeViewController: UIViewController {
    
    ///  表情键盘控制器
    private lazy var emoticonKeyboardVC: EmoticonViewController = EmoticonViewController { [unowned self](emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
    }
    // 懒加载照片选择器
    private lazy var photoSelectorVC:PhotoSelectorViewController = PhotoSelectorViewController()
    // 照片选择器视图
    private lazy var photoSelectorView: UIView = self.photoSelectorVC.view
    // 照片选择器视图高度约束
    private var photoSelectorViewHeightCons: NSLayoutConstraint?
    // toolBar 底部约束
    private var toolBarBottomCons: NSLayoutConstraint?
    
    //MARK:- 选择照片器
    func selectPhoto() {
        // 照片选择器占屏幕1/3
        photoSelectorViewHeightCons?.constant = view.bounds.height / 3
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 调整toolBar的约束
        toolBarBottomCons?.constant = 0
    }
    
    ///  切换表情视图 
    func inputEmoticon() {
        // 如果输入视图为nil 说明使用的是系统键盘
        print(textView.inputView)
        // 切换键盘前需要关闭当前键盘
        textView.resignFirstResponder()
        // 更换键盘输入视图
        textView.inputView = (textView.inputView == nil) ? emoticonKeyboardVC.view : nil
        // 重新设置焦点
        textView.becomeFirstResponder()
    }
    override func loadView() {
        super.loadView()
        view = UIView()
        
        // 添加子控制器
        addChildViewController(emoticonKeyboardVC)
        addChildViewController(photoSelectorVC)
        view.addSubview(photoSelectorView)
        prepareUI()
    }
    
    //MARK:- 键盘处理
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    /// 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 本地键盘切换标记 - 以下函数专用
    private var localKeyboardFlag = false
    /// 键盘变化通知方法
    func keyboardChanged(notification: NSNotification) {
        
        // 1.获取userInfo中UIKeyboardFrameEndUserInfoKey的值
        let rect = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        // 获取键盘动画时长
        var duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 取 UIKeyboardIsLocalUserInfoKey，如果为0，不做动画
        let local = notification.userInfo!["UIKeyboardIsLocalUserInfoKey"]!.boolValue
        // 判断是否退出键盘
        if !local {
            localKeyboardFlag = true
            return
        }
        // 根据localKeyboardFlag 设置动画时长
        duration = localKeyboardFlag ? 0 : duration
        localKeyboardFlag = false
        // 2.设置键盘高度
        toolBarBottomCons?.constant = -(view.bounds.height - rect.origin.y)
        
        // 3.设置动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK:- 发送微博按钮
    func sendClick () {
        print("发送")
        // 1.判断文本是否有内容
        if textView.emoticonText().characters.count <= 0 {
            return
        }
        // 2.判断文本内容是否足够长
        if textView.emoticonText().characters.count > statusMaxLength {
            SVProgressHUD.showInfoWithStatus("文本内容过长", maskType: SVProgressHUDMaskType.Black)
            return
        }
        SVProgressHUD.show()
        // 3.发送微博
        // 取到数组中的最后一张图片，新浪接口只允许发送一张
        let image = photoSelectorVC.photoes.last
        
        NetWorkTools.sharedNetWorkTools.postStatus(textView.emoticonText(),image: image) { (error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            // 发布成功后关闭窗口
            self.closeClick()
        }
    }
    
    //MARK:- 准备UI
    private func prepareUI() {
        // 取消自动调整滚动视图缩进
        automaticallyAdjustsScrollViewInsets = false
        
        prepareNavigationItem()
        prepareTextView()
        prepareToolBar()
        prepareOthers()
    }
    
    //MARK:- 准备其它控件
    private func prepareOthers() {
        // 添加字数提示label
        view.addSubview(lengthLabel)
        lengthLabel.text = "-10"
        // 设置布局
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -12, y: -12))
        
        // 设置照片查看器的布局
        photoSelectorView.ff_AlignVertical(ff_AlignType.TopCenter, referView: toolBar, size: nil)
        // 指定宽度和高度
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
        photoSelectorViewHeightCons = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 0)
        view.addConstraint(photoSelectorViewHeightCons!)
    }
    
    // 激活键盘
    // 第一次加载时激活键盘
    private var isFirstLoad = true
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if isFirstLoad {
            textView.becomeFirstResponder()
            isFirstLoad = false
        }
    }
    
    //MARK:- 准备textView
    private func prepareTextView() {
        self.view.addSubview(textView)
        // 手动设置间距
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        // 设置textView的布局
        textView.ff_AlignInner(ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(ff_AlignType.TopRight, referView: photoSelectorView, size: nil)

        placeHolderLabel.text = "分享新鲜事"
        placeHolderLabel.textColor = UIColor.lightGrayColor()
        placeHolderLabel.sizeToFit()
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil,offset: CGPoint(x: 5, y: 8))
    }
    
    //MARK:- 准备工具条
    private func prepareToolBar() {
        toolBar.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
        
        let itemSettings = [["imageName":"compose_toolbar_picture","action":"selectPhoto"],
            ["imageName":"compose_mentionbutton_background"],["imageName":"compose_trendbutton_background"],["imageName":"compose_emoticonbutton_background","action":"inputEmoticon"],["imageName":"compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        
        for s in itemSettings {
            items.append(UIBarButtonItem(imageName: s["imageName"]!, highlightedImageName: nil, target: nil, actionName: s["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 删除最后一个弹簧
        items.removeLast()
        toolBar.items = items
        
        // 添加toolBar
        view.addSubview(toolBar)
        // 设置约束
        let cons = toolBar.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: nil)
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar": toolBar]))
        // 记录工具栏底部约束
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    }
    
    //MARK:- 准备导航栏
    private func prepareNavigationItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendClick")
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        // 导航栏标题设置
        let titleView = UIView(frame: CGRectMake(0, 0, 100, 44))
        let titleLabel = UILabel(textColor: UIColor.darkGrayColor(), fonSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        
        let nameLabel = UILabel(textColor: UIColor(white: 0.5, alpha: 1.0), fonSize: 13)
        nameLabel.text = sharedUserAccount?.name ?? ""
        nameLabel.sizeToFit()
        
        titleView.addSubview(nameLabel)
        titleView.addSubview(titleLabel)
        
        // 设置布局
        titleLabel.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil,offset: CGPoint(x: 0, y: -4))
        
        // 将titleView添加到navItem中
        navigationItem.titleView = titleView
    }
    
    //MARK:- dismiss控制器
    func closeClick() {
        SVProgressHUD.dismiss()
        // 关闭时 退出键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:- 懒加载TextView
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(16)
        tv.backgroundColor = UIColor.whiteColor()
        // 垂直滚动
        tv.alwaysBounceVertical = true
        // 滚动时关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        // 设置textView的代理
        tv.delegate = self
        return tv
    }()
    //MARK:- 懒加载toolBar
    private lazy var toolBar:UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 0, 44))
    //MARK:- 懒加载展位标签
    private lazy var placeHolderLabel = UILabel(textColor: UIColor.darkGrayColor(), fonSize: 17)
    //MARK:- 懒加载字数长度label
    private lazy var lengthLabel = UILabel(textColor: UIColor.redColor(), fonSize: 12)
}

// TextView 的代理方法
extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 判断字符数
        
        let length = statusMaxLength - textView.emoticonText().characters.count
        lengthLabel.text = (length == 0) ? "" : String(length)
        lengthLabel.textColor = length > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
    }
}